package jmsTopic;

import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.BasicConfigurator;

public class Publisher {

	private TopicConnectionFactory conFactory;
	private TopicConnection connection;
	private TopicSession session;
	private TopicPublisher publisher;
	
	public void sendObjectMessage(OneMessage msg, String topicName) throws NamingException, JMSException {

		InitialContext jndi = new InitialContext();
		
		try {
			conFactory = (TopicConnectionFactory) jndi.lookup("topicConnectionFactory");
		} catch (NamingException e) {
			System.exit(1);
		}
		
		try {
			connection = (TopicConnection) conFactory.createTopicConnection();
			session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
			
			Topic chatTopic = (Topic) jndi.lookup(topicName);	
			publisher = session.createPublisher(chatTopic);
			
			connection.start();
			
			ObjectMessage objMsg = session.createObjectMessage();
			objMsg.setObject(msg);
			publisher.send(objMsg);
	
			session.commit();
			
		} catch (JMSException e) {
			
		}
		
	}
	
	public static void main(String[] args) throws NamingException, JMSException{
		BasicConfigurator.configure();
		
		OneMessage oneMsg = new OneMessage();
		oneMsg.setFirstname("Liying");
		oneMsg.setLastname("zhang");
		oneMsg.setLogin("zhang");
		oneMsg.setPwd("root");
		
		try {
			Publisher pub = new Publisher();
			pub.sendObjectMessage(oneMsg, "MyTopic");
			
		} catch (NamingException e) {
			
		} catch (JMSException e) {
			
		} 
	}

}
